package com.honey.compilation.sql.ddl;

import com.honey.compilation.sql.SqlConstraint;
import com.honey.compilation.sql.SqlKeyWord;
import com.honey.compilation.sql.ValueElement;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.builder.CharacterBuilderFactory;
import com.honey.core.compiler.IndentSpace;
import com.honey.core.utils.StringUtility;

/**
 * UNIQUE 约束 
 * @author Administrator
 *
 */
public class ConstraintUnique extends SqlConstraint{
	
	private ValueElement uniqueName ;
	
	private static int index = 0;
	
	/** 是否添加随机的约束名称*/
	private boolean addRandomConstraintName = true;
	
	/**
	 * 默认的构造函数, 唯一键的名称使用随机数
	 */
	public ConstraintUnique (){
		
	}
	
	/**
	 * 构造函数,是否使用随机唯一约束名称 true:是  false:否<br />
	 * 如果指定唯一键的名称,随机生成唯一键名称失效,使用指定的唯一键名称. <br />
	 * @param addRandomConstraintName 是否添加随机的约束名称,true:是  false:否
	 */
	public ConstraintUnique (boolean addRandomConstraintName){
		this.addRandomConstraintName = addRandomConstraintName;
	}
	
	/**
	 * 构造函数,指定唯一键的名称<br />
	 * 如果指定唯一键的名称,随机生成唯一键名称失效,使用指定的唯一键名称.<br />
	 * @param uniqueName
	 */
	public ConstraintUnique (String uniqueName){
		if ( StringUtility.stringHasValue(uniqueName ) ){
			this.uniqueName = new ValueElement(uniqueName);
		}
	}
	
	/**
	 * 是否添加随机的约束名称,true:是  false:否<br/>
	 * 如果指定唯一键的名称,此参数失效,使用指定的唯一键名称.
	 * @return
	 */
	public boolean isAddRandomConstraintName() {
		return addRandomConstraintName;
	}

	/**
	 * 是否添加随机的约束名称,true:是  false:否<br />
	 * 如果指定唯一键的名称,此参数失效,使用指定的唯一键名称.
	 * @param addRandomConstraintName
	 */
	public void setAddRandomConstraintName(boolean addRandomConstraintName) {
		this.addRandomConstraintName = addRandomConstraintName;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.honey.core.dom.sql.SqlConstraint#getSQLConstraintType()
	 */
	@Override
	public SQLConstraintType getSQLConstraintType() {
		
		return SQLConstraintType.UNIQUE;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.honey.core.dom.CompilationElement#compiledContent(int)
	 */
	@Override
	public CharacterBuilder compiledContent(int indentLevel) {
		CharacterBuilder answer = CharacterBuilderFactory.createC16StringBuilder();
		IndentSpace.spaceIndent(answer, indentLevel);
		if( addRandomConstraintName && uniqueName == null){
			uniqueName = new ValueElement(
					CharacterBuilderFactory.createC16StringBuilder()
					.append(SqlKeyWord.OPERATION_UNDERSCORE)
					.append("un").append(index)
					.append(SqlKeyWord.OPERATION_UNDERSCORE)
					.append( StringUtility.getRandomString(6) )
					.append(SqlKeyWord.OPERATION_UNDERSCORE).toString()
			);
			index ++ ;
			answer.append(SqlKeyWord.CONSTRAINT )
			.append(uniqueName);
		}else if( uniqueName != null ){
			answer.append(SqlKeyWord.CONSTRAINT )
			.append(uniqueName);
		}

		answer.append(SqlKeyWord.UNIQUE);
		return answer ;
	}

}
